


#include <iostream>
#include <cmath>
#include <vector>
#include <iomanip>

#include "gfo_sca2att.hpp"
#include "Xvt.hpp"
#include "Vector.hpp"
#include "MJD.hpp"
#include "MiscMath.hpp"
#include "YDSTime.hpp"



using namespace gpstk;

void gfo_sca2att::convert(std::string filename)
{
   ifstream input(filename.c_str());
   if (!input)
   {
      FileMissingException
      fe ( "Cannot Open LEO Attitude file: " + filename );
      GPSTK_THROW(fe);
   }
   
   bool ok(true);
   
   string line;

   // jump the header
   while( !input.eof() && input.good() )
   {
      if( input.eof() ) break;
      if( input.bad() ) { ok = false; break; }
      
      getline( input, line );

      if(line[0] == '#') break;
   }
   
   // now, read the data line
   while( !input.eof() && input.good() )
   {
      if( input.eof() ) break;
      if( input.bad() ) { ok = false; break; }
      
      getline( input, line );
      istringstream iss(line);
      double sec;
      double q0, q1, q2, q3, qrss;
      string qflag;
      string graceid, scaid;

      iss >> sec >> graceid >> scaid >> q0 >> q1 >> q2 >> q3 >> qrss >> qflag;

      if(pAttStream!=NULL)
      {
          CommonTime epoch = secondToCommonTime(sec);
          YDSTime ydsTime(epoch);

          (*pAttStream) 
              << fixed
              << ydsTime.year << " "
              << ydsTime.doy  << " "
              << setprecision(1)
              << ydsTime.sod  << " "
              << setprecision(16)
              << q0 << " "
              << setprecision(17)
              << q1 << " "
              << q2 << " "
              << q3  << " "
              << qrss << " "
              << qflag << " "
              << endl;
      }
      else
      {
          cerr << "please input pAttStream" << endl;
          exit(-1);
      }
      
   }
   
   input.close();
   
   if( !ok )
   {
      FileMissingException fe( filename + "is corrupted..." );
      GPSTK_THROW(fe);
   }
   
} // END of "loadFile"


CommonTime gfo_sca2att::secondToCommonTime( long double s)
{
   MJD TimeMJD(TimeOriginMJD + s/86400.0, TimeSystem::GPS);
   return TimeMJD.convertToCommonTime();
   
} // END of "gfo_sca2att::secondToCommonTime"


long double gfo_sca2att::CommonTimeToSecond( CommonTime& t )
{
   MJD TimeMJD;
   TimeMJD.convertFromCommonTime( t );
   return (TimeMJD.mjd - TimeOriginMJD)*86400.0;
}





















